import { createRouter, createWebHistory } from "vue-router";
import type { RouteRecordRaw } from "vue-router";
import { useMenuStore } from '../store/index'
import Home from '../menu/HomeVue/index.vue'
import { getRouter } from '../api/ce'

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "home",
    component: Home,
    children :[
    ]
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login/index.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  let token = localStorage.getItem('token')
  const store = useMenuStore()
  
  if (to.path === '/login') {
    // 如果是访问登录界面，如果用户会话信息存在，代表已登录过，跳转到主页
    if (token) {
      next({
        path: '/'
      })
    } else {
      next()
    }
  } else {
    if (!token) {
      // 如果访问非登录界面，且户会话信息不存在，代表未登录，则跳转到登录界面
      console.log("登录界面")
      next({
        path: '/login'
      })
    }
    else if(!store.menuList.length){       
      getRouterList().then((res:any) => {
        console.log(res);
        store.$patch(state => {
          state.menuList = res
          console.log(store.menuList.length);
        })
         // 加载动态菜单和路由
         addDynamicMenuAndRoutes(res);
         //坑：直接使用next()刷新后会一直白屏
         next({ ...to,replace:true});
      })
    }
    else{
      next();
    }
  }
});

// 动态获取菜单
function getRouterList(){
  return new Promise((resolve, reject) => {
    getRouter({}).then( (res:any) => {
      resolve(res.data);
    }).catch((error) => {
      reject(error);
    });
  })
}

function addDynamicMenuAndRoutes(menuTreeData){
  let dynamicRouters=addDynamicRoutes(menuTreeData);
  //将路由添加到Home的children中去
  router.options.routes[0].children=router.options.routes[0].children.concat(dynamicRouters)
  //添加到路由（因版本问题，可能写成router.addRoutes,多一个s）
  router.addRoute(router.options.routes[0]);
  console.log("所有路由加载完成");
  console.log(router.options.routes);
}

function addDynamicRoutes(menuList = [], routes = []){
  //用于筛选出最底层的children 
  // var temp = [];
  for (let i = 0; i < menuList.length; i++) {
    // 判断地址是否存在
    if (menuList[i].path) {
      // 创建路由配置
      //踩坑记1：必须要写成@/views/${变量}
      var route = {
        path: menuList[i].path,
        name: menuList[i].name,
        component: () => import("../views"+ menuList[i].path + "/index.vue"),
        meta: {
          icon: menuList[i].icon || ""
          }
      }
      routes.push(route);
    }
  }
  //将筛选出来的children进行重复调用
  // if (temp.length >= 1) {
  //   addDynamicRoutes(temp, routes)
  // } else {
    console.log('动态路由加载...')
    console.log(routes)
    console.log('动态路由加载完成.')
  // }
  return routes
}

export default router;
